"""
剪映模板数据模型

定义剪映模板和视频片段的数据结构。
"""

from datetime import datetime
from typing import Dict, Any, List, Optional
import json

from sqlalchemy import Column, Integer, String, Text, Float, Boolean, ForeignKey
from sqlalchemy.orm import relationship

from .base import BaseModel


class JianyingTemplate(BaseModel):
    """
    剪映模板模型
    
    存储剪映模板的基本信息和分析结果
    """
    
    __tablename__ = 'jianying_templates'
    
    # 基本信息
    template_id = Column(String(255), unique=True, nullable=False, index=True)
    template_name = Column(String(255), nullable=False)
    template_path = Column(Text, nullable=False)
    template_description = Column(Text, nullable=True)
    
    # 项目属性
    duration_seconds = Column(Float, nullable=True)
    fps = Column(Float, nullable=True)
    project_id = Column(String(255), nullable=True)
    
    # 画布信息
    canvas_width = Column(Integer, nullable=True)
    canvas_height = Column(Integer, nullable=True)
    canvas_ratio = Column(String(50), nullable=True)
    
    # 轨道统计
    tracks_count = Column(Integer, nullable=True)
    video_tracks_count = Column(Integer, nullable=True)
    audio_tracks_count = Column(Integer, nullable=True)
    
    # 素材统计
    materials_count = Column(Integer, nullable=True)
    video_segments_count = Column(Integer, nullable=True)
    effects_count = Column(Integer, nullable=True)
    
    # 时间信息
    creation_time = Column(Integer, nullable=True)  # 原始时间戳
    modification_time = Column(Integer, nullable=True)  # 原始时间戳
    
    # 状态字段
    is_enabled = Column(Boolean, nullable=False, default=True)  # 是否启用

    # JSON数据字段
    device_info = Column(Text, nullable=True)  # JSON格式的设备信息
    analysis_data = Column(Text, nullable=True)  # JSON格式的完整分析数据
    replacement_template = Column(Text, nullable=True)  # JSON格式的替换模板
    
    # 关联关系
    video_segments = relationship("JianyingVideoSegment", back_populates="template", cascade="all, delete-orphan")
    
    def get_device_info(self) -> Dict[str, Any]:
        """获取设备信息字典"""
        if self.device_info:
            try:
                return json.loads(self.device_info)
            except json.JSONDecodeError:
                return {}
        return {}
    
    def set_device_info(self, device_info: Dict[str, Any]):
        """设置设备信息"""
        self.device_info = json.dumps(device_info, ensure_ascii=False)
    
    def get_analysis_data(self) -> Dict[str, Any]:
        """获取分析数据字典"""
        if self.analysis_data:
            try:
                return json.loads(self.analysis_data)
            except json.JSONDecodeError:
                return {}
        return {}
    
    def set_analysis_data(self, analysis_data: Dict[str, Any]):
        """设置分析数据"""
        self.analysis_data = json.dumps(analysis_data, ensure_ascii=False)
    
    def get_replacement_template(self) -> Dict[str, Any]:
        """获取替换模板字典"""
        if self.replacement_template:
            try:
                return json.loads(self.replacement_template)
            except json.JSONDecodeError:
                return {}
        return {}
    
    def set_replacement_template(self, replacement_template: Dict[str, Any]):
        """设置替换模板"""
        self.replacement_template = json.dumps(replacement_template, ensure_ascii=False)
    
    def to_dict(self, include_relationships: bool = False) -> Dict[str, Any]:
        """转换为字典"""
        result = super().to_dict(include_relationships)
        
        # 解析JSON字段
        result['device_info'] = self.get_device_info()
        result['analysis_data'] = self.get_analysis_data()
        result['replacement_template'] = self.get_replacement_template()
        
        if include_relationships and self.video_segments:
            result['video_segments'] = [segment.to_dict() for segment in self.video_segments]
        
        return result


class JianyingVideoSegment(BaseModel):
    """
    剪映视频片段模型
    
    存储视频片段的详细信息
    """
    
    __tablename__ = 'jianying_video_segments'
    
    # 关联信息
    template_id = Column(String(255), ForeignKey('jianying_templates.template_id'), nullable=False, index=True)
    
    # 片段基本信息
    segment_index = Column(Integer, nullable=False)
    segment_id = Column(String(255), nullable=False)
    
    # 素材信息
    material_id = Column(String(255), nullable=True, index=True)
    local_material_id = Column(String(255), nullable=True, index=True)
    material_name = Column(String(255), nullable=True)
    material_path = Column(Text, nullable=True)
    
    # 时间信息
    target_start = Column(Float, nullable=True)
    target_duration = Column(Float, nullable=True)
    target_end = Column(Float, nullable=True)
    source_start = Column(Float, nullable=True)
    source_duration = Column(Float, nullable=True)
    
    # 素材属性
    material_width = Column(Integer, nullable=True)
    material_height = Column(Integer, nullable=True)
    material_fps = Column(Float, nullable=True)
    material_has_audio = Column(Boolean, nullable=True)
    
    # 变换信息
    transform_x = Column(Float, nullable=True)
    transform_y = Column(Float, nullable=True)
    transform_scale_x = Column(Float, nullable=True)
    transform_scale_y = Column(Float, nullable=True)
    transform_rotation = Column(Float, nullable=True)
    
    # 特效信息
    effects_count = Column(Integer, nullable=True)
    effects_data = Column(Text, nullable=True)  # JSON格式的特效数据
    
    # 关联关系
    template = relationship("JianyingTemplate", back_populates="video_segments")
    
    def get_effects_data(self) -> List[str]:
        """获取特效数据列表"""
        if self.effects_data:
            try:
                return json.loads(self.effects_data)
            except json.JSONDecodeError:
                return []
        return []
    
    def set_effects_data(self, effects_data: List[str]):
        """设置特效数据"""
        self.effects_data = json.dumps(effects_data, ensure_ascii=False)
    
    def to_dict(self, include_relationships: bool = False) -> Dict[str, Any]:
        """转换为字典"""
        result = super().to_dict(include_relationships)
        
        # 解析JSON字段
        result['effects_data'] = self.get_effects_data()
        
        return result
